const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const koajwt = require('koa-jwt')
const { TOKEN_SECRET_KEY } = require('./conf/secretKeys')

// 引入路由
const UserAPIRouter = require('./routes/api/user')
const PyqAPIRouter = require('./routes/api/pyq')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
    extension: 'ejs'
}))


app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*')
    await next()
})

app.use(async (ctx, next)=> {
    ctx.set('Access-Control-Allow-Origin', 'http://127.0.0.1:5500')
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild')
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
    ctx.set('Access-Control-Allow-Credentials', true)
    if (ctx.method.toUpperCase() == 'OPTIONS') {
        ctx.body = 200
    } else {
        await next()
    }
})

// logger
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 错误处理
app.use((ctx, next) => {
    return next().catch((err) => {
        if(err.status === 401){
            ctx.status = 401
      		ctx.body = '无访问权限！\n'
        }else{
            throw err
        }
    })
})

// token验证
app.use(koajwt({
    secret: TOKEN_SECRET_KEY
}).unless({
    // 不需要JWT验证的接口
    path: [
        /^\/api\/user\/login$/,
        /^\/api\/user\/register$/
    ]
}))

// 注册路由
app.use(UserAPIRouter.routes(), UserAPIRouter.allowedMethods())
app.use(PyqAPIRouter.routes(), PyqAPIRouter.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
})

module.exports = app
